package com.dcz.fileportal.downloader;

import android.content.Context;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadQueueSet;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class Downloader {

    public static void setup(Context context) {
        FileDownloader.setup(context);
    }


    public static void startDownload(String dataUrl, String destPath, SimpleFileDownloadListener downloadListener) {
        FileDownloader.getImpl().create(dataUrl)
                .setPath(destPath)
                .setListener(downloadListener)
                .start();
    }

    public static void startMultiDownload(List<String> dataUrlList, String destPath, FileDownloadListener downloadListener) {
        // 创建下载任务
        List<BaseDownloadTask> tasks = new ArrayList<>();
        for (String url : dataUrlList) {
            tasks.add(FileDownloader.getImpl().create(url)
                    .setPath(destPath + UUID.randomUUID() + ".png")
                    .setListener(downloadListener));
        }

        // 创建下载队列
        FileDownloadQueueSet queueSet = new FileDownloadQueueSet(downloadListener);

        // 配置队列参数
        queueSet.disableCallbackProgressTimes(); // 防止每个任务都回调 progress，提高效率
        queueSet.setAutoRetryTimes(1); // 所有任务失败时自动重试一次

        // 将任务添加到队列中
        queueSet.downloadTogether(tasks);

        // 启动队列
        queueSet.start();
    }


    public static void pauseDownload(String dataUrl, String destPath) {
        FileDownloader.getImpl().pause(FileDownloadUtils.generateId(dataUrl, destPath));
    }

    public static boolean isDownloading(String dataUrl, String destPath) {
        return FileDownloader.getImpl().getStatus(dataUrl, destPath) > 0;
    }

    public static long getTotal(String dataUrl, String destPath) {
        return FileDownloader.getImpl().getTotal(FileDownloadUtils.generateId(dataUrl, destPath));
    }

    public static long getSoFar(String dataUrl, String destPath) {
        return FileDownloader.getImpl().getSoFar(FileDownloadUtils.generateId(dataUrl, destPath));
    }

    public static int getId(String dataUrl, String destPath) {
        return FileDownloadUtils.generateId(dataUrl, destPath);
    }
}
